package fm.yichenet.controller;

import fm.controller.BaseController;
import fm.entity.CashApplication;
import fm.dto.NeiyiUser;
import fm.entityEnum.CrashStatusEnum;
import fm.exception.BizException;
import fm.web.CurrentRequest;
import fm.yichenet.service.CashApplicationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by CM on 2017/6/29.
 */
@Controller
@RequestMapping("/cash/application")
public class CashApplicationController extends BaseController {
    @Autowired
    private CashApplicationService cashApplicationService;

    @ResponseBody
    @RequestMapping("/list")
    public Map getList(String userId, String startTime, String endTime, CrashStatusEnum status,
                       @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                       @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        Map res = new HashMap();
        try {
            if (userId == null) {
                if (CurrentRequest.getCurrentUser() instanceof NeiyiUser) {
                    userId = (String) CurrentRequest.getCurrentUserId();
                }
            }
            List<CashApplication> aps = cashApplicationService.getUserCashApplications(userId, startTime, endTime, status, pageNum, pageSize);
            res.put("data", aps);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }


    @ResponseBody
    @RequestMapping("/add")
    public Map addCashApplication(@RequestBody CashApplication application) {
        Map res = new HashMap();
        try {
            application = cashApplicationService.add(application);
            res.put("data", application);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }

}
